package com.yourenbang.lingyun.transaction.web.service.impl.migrate;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.parser.ParserConfig;
import com.yourenbang.lingyun.core.util.BizAssertUtils;
import com.yourenbang.lingyun.core.util.KLog;
import com.yourenbang.lingyun.core.util.redis.RedisUtils;
import com.yourenbang.lingyun.domain.McenterJiguangBind;
import com.yourenbang.lingyun.domain.McenterJiguangBindExample;
import com.yourenbang.lingyun.mapper.McenterJiguangBindMapper;
import com.yourenbang.lingyun.mapper.UserBaseExtMapper;
import com.yourenbang.lingyun.transaction.config.AcmTransactionParams;
import com.yourenbang.lingyun.transaction.web.domain.dto.migrate.kuaishou.QueryTableDateDTO;
import com.yourenbang.lingyun.transaction.web.domain.dto.migrate.kuaishou.QueryTablePageDTO;
import com.yourenbang.lingyun.transaction.web.domain.po.klks.MsgPushBindPO;
import com.yourenbang.lingyun.transaction.web.service.migrate.MsgPushBindBatchMigrateService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description
 * @Date 2020/12/5 14:56
 * @Created by Jason
 */
@Service
@Slf4j
public class MsgPushBindBatchMigrateServiceImpl extends AbstractMigrateService implements MsgPushBindBatchMigrateService {

    @Autowired
    private RedisUtils redis;
    @Autowired
    private AcmTransactionParams acmTransactionParams;
    @Autowired
    private UserBaseExtMapper userBaseExtMapper;
    @Autowired
    private CommonMigrateServiceImpl commonMigrateService;
    @Autowired
    private McenterJiguangBindMapper mcenterJiguangBindMapper;

    @Override
    public boolean migratePushBindPage(QueryTablePageDTO dto) {
        String uri = "/query/pay/push/bind/limit";
        String url = acmTransactionParams.getKaolakuaishouHost() + uri;
        JSONArray jsonArray = commonMigrateService.pullDataFromKS(url, dto.toJSON());
        if (jsonArray.size() == 0) {
            return false;
        }
        //parse（字符串转对象）的时候 设置下划线转驼峰
        ParserConfig.getGlobalInstance().propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;

        List<MsgPushBindPO> pushBinds = jsonArray.toJavaList(MsgPushBindPO.class);

        savePush(pushBinds);
        return true;
    }

    @Override
    public boolean migratePushBindOrder(QueryTableDateDTO dto) {
        String uri = "/query/pay/push/bind/order";
        String url = acmTransactionParams.getKaolakuaishouHost() + uri;
        JSONArray jsonArray = commonMigrateService.pullDataFromKS(url, dto.toJSON());
        if (jsonArray.size() == 0) {
            return false;
        }
        //parse（字符串转对象）的时候 设置下划线转驼峰
        ParserConfig.getGlobalInstance().propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;

        List<MsgPushBindPO> pushBinds = jsonArray.toJavaList(MsgPushBindPO.class);

        savePush(pushBinds);
        return true;
    }


    /**
     * 批量插入极光推送
     *
     * @param pushBinds
     */
    private void savePush(List<MsgPushBindPO> pushBinds) {
        List<McenterJiguangBind> mcenterJiguangBinds = new ArrayList<>();
        for (MsgPushBindPO pushBindPO : pushBinds) {
            try {
                McenterJiguangBind mcenterJiguangBind = new McenterJiguangBind();
                String userBaseId = getUserBaseId(userBaseExtMapper, pushBindPO.getUserId(), redis);
                mcenterJiguangBind.setAppType(pushBindPO.getAppType());
                mcenterJiguangBind.setAlias(pushBindPO.getAlias());
                mcenterJiguangBind.setClientSystem(pushBindPO.getClientSystem().concat("0"));
                mcenterJiguangBind.setUserBaseId(userBaseId);
                mcenterJiguangBind.setIsDel(Boolean.FALSE);
                mcenterJiguangBind.setCreateTime(pushBindPO.getCreateTime());
                mcenterJiguangBind.setUpdateTime(LocalDateTime.now());
                McenterJiguangBindExample jiguangBindExample = new McenterJiguangBindExample();
                jiguangBindExample.createCriteria()
                        .andUserBaseIdEqualTo(mcenterJiguangBind.getUserBaseId())
                        .andAppTypeEqualTo(mcenterJiguangBind.getAppType());
                List<McenterJiguangBind> jiguangBindList = mcenterJiguangBindMapper.selectByExample(jiguangBindExample);
                if (CollectionUtils.isEmpty(jiguangBindList)) {
                    mcenterJiguangBinds.add(mcenterJiguangBind);
                } else {
                    mcenterJiguangBind.setMcenterJiguangBindId(jiguangBindList.get(0).getMcenterJiguangBindId());
                    int i = mcenterJiguangBindMapper.updateByPrimaryKeySelective(mcenterJiguangBind);
                    BizAssertUtils.assertOne(i, "更新极光推送失败");
                }
            } catch (Exception e) {
                KLog.error("迁移推送失败,极光推送记录:{}", pushBindPO, e);
            }

        }
        if (mcenterJiguangBinds.size() != 0) {
            int i = mcenterJiguangBindMapper.batchInsert(mcenterJiguangBinds);
            KLog.info("共[{}]条,更新[{}]条推送记录结束", mcenterJiguangBinds.size(), i);
        }
    }
}
